<template>
  <page-header-wrapper :title="false">
    <div class="Role">
      <a-spin tip="操作中..." class="position" v-if="roleLoading"> </a-spin>
      <a-modal
        width="1200px"
        v-model="modleVisible"
        :title="form.id ? '编辑充电柜' : '新增充电柜'"
        @cancel="() => (this.modleVisible = false)"
        :confirm-loading="formButtonDisableFlag"
        @ok="onSubmit"
        destroyOnClose
      >
        <div id="modalContent">
          <div class="formAspin" v-if="editWaitForLoading">
            <a-spin />
          </div>
          <div class="modalContentForm">
            <a-form-model
              ref="formRef"
              :model="form"
              :rules="rules"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 18 }"
            >
              <a-row type="flex" justify="space-between">
                <a-col :span="24" v-show="addType">
                  <a-radio-group v-model="addType" style="padding: 0 0px 20px 31px" @change="addTypeChange">
                    <a-radio-button value="single"> 单个新增 </a-radio-button>
                    <a-radio-button value="multiple"> 批量新增 </a-radio-button>
                  </a-radio-group>
                </a-col>
                <template v-if="!addType || addType == 'single'">
                  <a-col :span="12">
                    <Input :form="form" label="充电柜名称" prop="name" placeholder="请输入充电柜名称"></Input>
                  </a-col>
                  <a-col :span="12">
                    <!-- <InputNumber
                      :form="form"
                      label="充电柜编号"
                      prop="code"
                      :min="1000000000000000"
                      :max="9999999999999999"
                      placeholder="请输入充电柜编号"
                    ></InputNumber> -->
                    <Input
                      :form="form"
                      label="充电柜编号"
                      prop="code"
                      :readonly="form.id ? true : false"
                      placeholder="请输入充电柜编号"
                    ></Input>
                  </a-col>
                </template>
                <template v-if="addType == 'multiple'">
                  <a-col :span="12">
                    <Input
                      :form="form"
                      label="充电柜名称"
                      prop="name"
                      placeholder="请输入充电柜名称"
                      suffix="0000"
                    ></Input>
                  </a-col>
                  <a-col :span="12">
                    <!-- <InputNumber
                      :form="form"
                      label="充电柜编号"
                      prop="code"
                      :min="1000000000000"
                      :max="9999999999999"
                      placeholder="请输入充电柜编号"
                    ></InputNumber> -->
                    <Input :form="form" label="充电柜编号" prop="code" placeholder="请输入充电柜编号"></Input>
                  </a-col>
                  <a-col :span="12">
                    <InputNumber
                      :form="form"
                      label="增加充电柜个数"
                      prop="chargingCabinetNumber"
                      :min="2"
                      :max="999"
                      :rules="{
                        required: true,
                        message: '请输入增加充电柜个数',
                        trigger: 'blur',
                      }"
                      placeholder="请输入增加充电柜个数"
                    ></InputNumber>
                  </a-col>
                </template>
                <a-col :span="12">
                  <treeSelect
                    :form="form"
                    label="所属组织"
                    prop="organizationId"
                    :treeData="oDictionary.organizationsTree"
                    placeholder="请选择组织"
                    @change="(e) => dynamicLoadingCharges(true, e)"
                  ></treeSelect>
                </a-col>
                <a-col :span="12">
                  <Select
                    :form="form"
                    label="设备型号"
                    prop="chargingCabinetModeId"
                    :optList="oDictionary.allCabinetModels"
                    placeholder="请选择设备型号"
                    @change="setBinCount"
                  ></Select>
                </a-col>
                <a-col :span="12">
                  <Input
                    :form="form"
                    label="格口个数"
                    prop="binCount"
                    placeholder="选择设备型号自动读取"
                    readonly
                  ></Input>
                </a-col>
                <a-col :span="12">
                  <Select
                    :form="form"
                    label="场站网点"
                    prop="chargingNetworkId"
                    :optList="oDictionary.dynamicNetworksAll"
                    placeholder="选择组织机构后查询场站网点"
                    :loading="networksAllLoading"
                  ></Select>
                </a-col>
                <a-col :span="12">
                  <Select
                    :form="form"
                    label="是否私有"
                    prop="isPrivate"
                    :optList="enumsTypeJson['YES_OR_NO']"
                    placeholder="选择充电柜是否私有"
                  ></Select>
                </a-col>
                <a-col :span="12">
                  <Select
                    :form="form"
                    label="收费类型"
                    prop="chargeType"
                    :optList="enumsTypeJson['CHARGING_CABINET_CHARGE_TYPE']"
                    placeholder="选择收费类型"
                  ></Select>
                </a-col>

                <a-col :span="12">
                  <Select
                    :form="form"
                    label="资费模板"
                    prop="chargeTmplId"
                    :optList="oDictionary.allCharges"
                    placeholder="选择组织机构后资费模板"
                    :loading="allChargesLoading"
                  ></Select>
                </a-col>
                <a-col :span="12">
                  <datePicker
                    :form="form"
                    label="出厂日期"
                    prop="productioDate"
                    placeholder="请选择出厂日期"
                  ></datePicker>
                </a-col>
                <a-col :span="12">
                  <datePicker
                    :form="form"
                    label="安装日期"
                    prop="installDate"
                    placeholder="请选择安装日期"
                  ></datePicker>
                </a-col>
                <a-col :span="12">
                  <datePicker
                    :form="form"
                    label="保修到期"
                    prop="repaireEndDate"
                    placeholder="请选择保修到期"
                  ></datePicker>
                </a-col>
                <a-col :span="12" v-if="form.id">
                  <!-- 编辑回显，新增不显示此字段 -->
                  <Input
                    :form="form"
                    :readonly="true"
                    label="SIM卡ICCID"
                    prop="chargingCabinetStateIccid"
                    placeholder="请输入SIM卡ICCID"
                  ></Input>
                </a-col>
                <a-col :span="12">
                  <datePicker
                    :form="form"
                    label="SIM卡到期"
                    prop="simExpireDate"
                    placeholder="请选择SIM卡到期"
                  ></datePicker>
                </a-col>
                <a-col :span="24">
                  <!-- <a-col :span="12">
                    <Select
                      :form="form"
                      label="安全模板"
                      prop="userTemplate"
                      :optList="oDictionary.allCabinetSecurities"
                      placeholder="请选择安全模板"
                      @change="setUserTemplate"
                    ></Select>
                  </a-col> -->
                  <!-- <a-col :span="12">
                    <Input
                      :form="form"
                      label="登录用户名"
                      prop="loginName"
                      placeholder="选择安全模板自动读取"
                      readonly
                    ></Input>
                  </a-col>
                  <a-col :span="12">
                    <Input
                      :form="form"
                      label="登录密码"
                      prop="loginPass"
                      placeholder="选择安全模板自动读取"
                      readonly
                    ></Input>
                  </a-col> -->
                </a-col>
                <a-col :span="24">
                  <!-- <a-col :span="12">
                    <Input
                      :form="form"
                      label="密钥"
                      prop="aesKey"
                      placeholder="选择安全模板自动读取"
                      readonly
                    ></Input>
                  </a-col> -->
                </a-col>
                <!-- <a-col :span="12">
                  <Select
                    :form="form"
                    label="状态"
                    prop="isEnable"
                    placeholder="请选择状态"
                    :optList="getIsEnableOption()"
                  ></Select>
                </a-col> -->
                <a-col :span="12">
                  <Input :form="form" label="地址" prop="address" placeholder="请输入地址"></Input>
                </a-col>
                <a-col :span="12">
                  <Input :form="form" label="备注" prop="remark" placeholder="请输入备注"></Input>
                </a-col>
                <a-col :span="24">
                  <a-col :span="12">
                    <Input :form="form" label="经度" prop="lng" placeholder="点击地图自动生成经度" readonly></Input>
                  </a-col>
                  <a-col :span="12">
                    <Input :form="form" label="纬度" prop="lat" placeholder="点击地图自动生成纬度" readonly></Input>
                  </a-col>
                </a-col>
              </a-row>
            </a-form-model>
            <MapBox ref="map" @click="mapClick"></MapBox>
          </div>
        </div>
      </a-modal>
      <typicalSearch
        ref="insideSearch"
        :searchConfig="searchConfig"
        :isDelete="isDelete"
        @searchMethod="getTableData"
        @clearMethod="searchOptListDynamicLoading()"
      ></typicalSearch>
      <div class="table">
        <div class="tableTitle">
          <div class="title">充电柜管理</div>
          <div class="addButton">
            <!--<span style="margin-right: 8px" v-show="selectedRowKeys.length > 0">
              {{ `当前选择 ${selectedRowKeys.length} 条数据` }}
            </span>
            <a-popconfirm
              slot="action"
              title="此操作将删除已勾选的数据，是否继续?"
              ok-text="是"
              cancel-text="否"
              @confirm="batchDelete"
            >
              <Button
                type="batchDelete"
                label="批量删除"
                :disabled="selectedRowKeys.length === 0 || isLoading"
                :loading="isLoading"
              >
              </Button>
            </a-popconfirm>-->
            <a-button type="primary" @click="handleEdit()" style="margin-left: 5px"> 新增充电柜 </a-button>
          </div>
        </div>
        <div class="tableList">
          <typicalTable
            ref="insideTable"
            :tableConfig="tableConfig"
            :tableData="tableData"
            @getTableData="getTableData"
            @selectionChange="tableChange"
          >
            <template v-slot="slotProps">
              <Button label="编辑" @click="handleEdit(slotProps.record)"></Button>
              <a-popconfirm
                slot="action"
                title="此操作将删除该条数据，是否继续?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(slotProps.record)"
              >
                <Button type="stop" label="删除"></Button>
              </a-popconfirm>
              <Button
                v-if="slotProps.record.isEnable == 0"
                type="start"
                @click="fnStartStop(slotProps.record)"
              ></Button>
              <Button
                v-else-if="slotProps.record.isEnable == 1"
                type="stop"
                @click="fnStartStop(slotProps.record)"
              ></Button>
            </template>
          </typicalTable>
        </div>
      </div>
    </div>
  </page-header-wrapper>
</template>
<script>
import { allCabinetSecurities, batchCreateCabinet } from '@/api/api';
import moment from 'moment';
import typicalSearch from '@/components/typicalSearch';
import typicalTable from '@/components/typicalTable';
import Input from '@/components/typicalControl/Input';
import InputNumber from '@/components/typicalControl/InputNumber';
import treeSelect from '@/components/typicalControl/treeSelect';
import datePicker from '@/components/typicalControl/datePicker';
import Select from '@/components/typicalControl/select';
import MapBox from '@/components/map';
import Button from '@/components/typicalControl/button';
import { getIsEnableOption } from '@/utils/frequentInterface';
import { recursionTreeDisabled, objectSubAttributeAssign, supplementZero } from '@/utils/tool';

import { organizationsTree } from '@/api/system';
import {
  listCabinets,
  listNetworksAll,
  allCharges,
  listCabinetModels,
  equipControl,
  listCharges,
  listEnumsByType,
} from '@/api/cabin';
export default {
  name: 'ChargingCabinet',
  components: {
    typicalSearch: typicalSearch,
    typicalTable: typicalTable,
    Input: Input,
    InputNumber: InputNumber,
    treeSelect: treeSelect,
    datePicker: datePicker,
    Button: Button,
    Select: Select,
    MapBox: MapBox,
  },
  data() {
    return {
      isLoading: false,
      allChargesLoading: false, // 资费字段加载
      networksAllLoading: false, // 场站字段加载
      formButtonDisableFlag: false, // 表单确定禁用按钮 防止多次点击多次保存
      editWaitForLoading: false, // 加载编辑回显数据等待Loading
      roleLoading: false, // 加载表格的loading
      modleVisible: false, // 控制弹框
      addType: 'single',
      form: {
        // 表单数据
        name: '',
        code: '',
        organizationId: '',
        chargingCabinetModeId: '',
        binCount: '',
        chargingNetworkId: '',
        chargeTmplId: '',
        productioDate: '',
        installDate: '',
        repaireEndDate: '',
        // simIccid: '',
        simExpireDate: '',
        address: '',
        remark: '',
        lng: '',
        lat: '',

        isEnable: 1,
        isSystem: 0,
        chargeType: null, //组织内是否免费
        isPrivate: null, //是否组织内私有
        // aesKey: undefined,
        chargingCabinetNumber: undefined,
        // loginName: undefined,
        // loginPass: undefined,
        // userTemplate: undefined,
      },
      rules: {
        // 规则验证
        name: [
          { required: true, message: '请输入充电柜名称', trigger: 'blur' },
          { max: 15, message: '最大长度不能超过15个字', trigger: 'blur' },
        ],
        code: [
          { required: true, message: '请输入20位正确格式的充电柜编号', trigger: 'blur' },
          { max: 20, min: 20, message: '请输入20位正确格式的充电柜编号', trigger: 'blur' },
        ],
        organizationId: [{ required: true, message: '请选择所属组织', trigger: 'change' }],
        chargingCabinetModeId: [{ required: true, message: '请选择设备型号', trigger: 'change' }],
        chargingNetworkId: [{ required: true, message: '请选择场站网点', trigger: 'change' }],
        chargeTmplId: [{ required: true, message: '请选择资费模板', trigger: 'change' }],
        binCount: [{ required: true, message: '请选择设备型号自动读取', trigger: 'blur' }],
        // aesKey: [{ required: true, message: '请选择安全模板自动读取', trigger: 'blur' }],
        // loginName: [{ required: true, message: '请选择安全模板自动读取', trigger: 'blur' }],
        // loginPass: [{ required: true, message: '请选择安全模板自动读取', trigger: 'blur' }],
        lat: [{ required: true, message: '请点击地图自动生成纬度', trigger: 'blur' }],
        lng: [{ required: true, message: '请点击地图自动生成经度', trigger: 'blur' }],
        isPrivate: [{ required: true, message: '请选择充电柜是否私有', trigger: 'change' }],
        chargeType: [{ required: true, message: '是否组织内免费', trigger: 'change' }],
      },
      // 搜索组件配置
      searchConfig: {
        formItemList: [
          {
            type: 'selectTree',
            prop: 'searchOrganizationId',
            value: undefined,
            label: '所属组织',
            treeData: [],
            change: this.searchOptListDynamicLoading,
          },
          {
            type: 'select',
            prop: 'searchNetworkId',
            value: undefined,
            label: '场站网点',
            optList: [],
          },

          {
            type: 'input',
            prop: 'searchKeyWord',
            value: '',
            label: '名称或编码',
          },
          {
            type: 'select',
            prop: 'searchModelId',
            value: undefined,
            label: '设备型号',
            optList: [],
          },
        ],
        parent: this,
      },
      // 列表组件配置
      tableConfig: {
        columns: [
          {
            title: '充电柜编号',
            dataIndex: 'code',
            ellipsis: true,
          },
          {
            title: '充电柜名称',
            dataIndex: 'name',
            ellipsis: true,
          },
          {
            title: '所属组织',
            dataIndex: 'organName',
            ellipsis: true,
          },
          {
            title: '设备型号',
            dataIndex: 'modeName',
            ellipsis: true,
          },
          {
            title: '设备类型',
            dataIndex: 'typeName',
            ellipsis: true,
          },
          {
            title: '场站网点',
            dataIndex: 'networkName',
            ellipsis: true,
          },
          {
            title: '备注',
            dataIndex: 'remark',
            ellipsis: true,
          },
          {
            title: '状态',
            dataIndex: 'isEnable',
            width: '60px',
            scopedSlots: { customRender: 'status' },
          },
          {
            title: '操作',
            scopedSlots: { customRender: 'action' },
            ellipsis: true,
            width: '160px',
          },
        ],
        pageSize: this.$store.state.user.defaultPaginationPagesize,
        pageSizeOptions: this.$store.state.user.defaultPaginationOptions,
        parent: this,
        isSelection: true,
      },
      // 列表组件数据
      tableData: {
        records: [],
        total: 0,
      },
      oDictionary: {
        listNetworksAll: [],
        allCabinetTypes: [],
        organizationsTree: [],
        allCabinetSecurities: [],
        allCharges: [],
        allCabinetModels: [],
        dynamicNetworksAll: [],
        searchNetworksAll: [],
      },
      selectedRowKeys: [],
      enumsTypeJson: {},
      isDelete: false, //删除操作
    };
  },
  created() {
    this.getDictionary();
    this.getEnum();
  },
  mounted() {
    this.$refs.insideSearch.searchInfo();
  },
  methods: {
    getIsEnableOption,
    getEnum() {
      listEnumsByType().then((res) => {
        let datas = res.data;
        for (const key in datas) {
          for (var i = 0; i < datas[key].length; i++) {
            datas[key][i].name = datas[key][i].label;
          }
        }
        this.enumsTypeJson = datas;
      });
    },

    /**
     * [getDictionary 获取各种字典]
     * @return {[type]} [description]
     */
    getDictionary() {
      // 组织列表树形结构数据
      organizationsTree().then((res) => {
        if (res.code == 200) {
          recursionTreeDisabled(res.data);
          this.oDictionary.organizationsTree = res.data;
          for (var i = 0; i < this.searchConfig.formItemList.length; i++) {
            if (this.searchConfig.formItemList[i].prop == 'searchOrganizationId') {
              this.searchConfig.formItemList[i].treeData = res.data;
              break;
            }
          }
        }
      });
      // 场站网点
      this.getNetworkData();
      // 型号信息
      listCabinetModels('/getChargingCabinetModeList', 'get', {
        pageNum: 1,
        pageSize: 20,
        name: '',
        code: '',
        chargingCabinetTypeId: '',
      }).then((res) => {
        if (res.code == 200) {
          this.oDictionary.allCabinetModels = res.data.records.map((n) => {
            return {
              name: n.name,
              code: n.id,
              binCount: n.binCount,
            };
          });
          for (var i = 0; i < this.searchConfig.formItemList.length; i++) {
            if (this.searchConfig.formItemList[i].prop == 'searchModelId') {
              this.searchConfig.formItemList[i].optList = this.oDictionary.allCabinetModels;
            }
          }
        }
      });
      // 设备类型
      listCabinetModels('/getChargingCabinetModeList', 'get', {
        pageNum: 1,
        pageSize: 20,
        name: '',
        code: '',
        chargingCabinetTypeId: '',
      }).then((res) => {
        if (res.code == 200) {
          this.oDictionary.allCabinetTypes = res.data.records.map((n) => {
            return {
              name: n.name,
              code: n.id,
            };
          });
          // for (var i = 0; i < this.searchConfig.formItemList.length; i++) {
          //   if (this.searchConfig.formItemList[i].prop === 'searchModelId') {
          //     this.searchConfig.formItemList[i].optList = this.oDictionary.allCabinetTypes;
          //   }
          // }
        }
      });
      // 所有用户
      allCabinetSecurities().then((res) => {
        if (res.code == 200) {
          this.oDictionary.allCabinetSecurities = res.data.map((n) => {
            return {
              name: n.title,
              code: n.id,
              loginName: n.loginName,
              loginPass: n.loginPass,
              aesKey: n.aesKey,
            };
          });
        }
      });
    },
    getNetworkData(organizationId) {
      // 场站网点
      listNetworksAll(`/selectChargingnetwork`, 'get', {
        pageNum: 1,
        pageSize: 100,
        organizationId: organizationId,
      }).then((res) => {
        if (res.code == 200) {
          this.oDictionary.listNetworksAll = res.data.records.map((n) => {
            return {
              name: n.name,
              code: n.id,
            };
          });
          for (var i = 0; i < this.searchConfig.formItemList.length; i++) {
            if (this.searchConfig.formItemList[i].prop == 'searchNetworkId') {
              this.searchConfig.formItemList[i].optList = this.oDictionary.listNetworksAll;
              break;
            }
          }
        }
      });
    },
    /**
     * [searchOptListDynamicLoading 搜索下拉动态加载]
     * @param  {[type]} searchOrganizationId [组织机构id]
     * @return {[type]}                      [description]
     */
    searchOptListDynamicLoading(searchOrganizationId) {
      this.oDictionary.listNetworksAll = [];

      this.getNetworkData(searchOrganizationId);
    },
    /**
     * [dynamicLoadingCharges 动态加载表单组织机构下的资费模板，没有组织机构清空]
     * @param  {Boolean} isEmpty [是否清空选项]
     * @param  {[type]}  e       [选项]
     * @return {[type]}          [description]
     */
    dynamicLoadingCharges(isEmpty, e) {
      // this.form.organizationId =e;
      // if (isEmpty) {
      //   if (this.form.chargingCabinetModeId) this.form.chargingCabinetModeId = undefined;
      //   if (this.form.chargingNetworkId) this.form.chargingNetworkId = undefined;
      // }
      var searchOrganizationId = '';
      if (e) {
        searchOrganizationId = e;
      } else if (this.form.organizationId) {
        searchOrganizationId = this.form.organizationId;
      }
      // else {
      //   if (this.form.chargingCabinetModeId) this.form.chargingCabinetModeId = '';
      //   return;
      // }
      if (isEmpty) {
        this.form.chargingNetworkId = '';
        this.form.chargeTmplId = '';
      }
      // 资费
      this.allChargesLoading = true;
      this.oDictionary.dynamicNetworksAll = [];
      this.oDictionary.allCharges = [];
      listCharges(`/selectTmplByIds?organizationId=${searchOrganizationId}`, 'get')
        .then((res) => {
          if (res.code == 200) {
            this.oDictionary.allCharges = res.data.map((n) => {
              return {
                name: n.name,
                code: n.id,
                disabled: n.status !== 1,
              };
            });
          }
        })
        .finally(() => {
          this.allChargesLoading = false;
        });
      // 场站
      this.networksAllLoading = true;
      listNetworksAll('/selectChargingnetwork', 'get', {
        pageNum: 1,
        pageSize: 100,
        organizationId: searchOrganizationId,
      })
        .then((res) => {
          if (res.code == 200) {
            this.oDictionary.dynamicNetworksAll = res.data.records.map((n) => {
              return {
                name: n.name,
                code: n.id,
              };
            });
          }
        })
        .finally(() => {
          this.networksAllLoading = false;
        });
    },

    /**
     * [fnStartStop 启用停用方法]
     * @param  {[type]} row [行数据]
     * @return {[type]}     [description]
     */
    fnStartStop(row) {
      let msg = row.isEnable == 0 ? '启用' : '停用';
      this.$confirm({
        title: '提示',
        content: (h) => `确定要${msg}吗？`,
        onOk: () => this.doStartStope(row),
        centered: true,
        maskClosable: true,
      });
    },
    doStartStope(row) {
      this.roleLoading = true;
      let url = row.isEnable == 0 ? '/enable' : '/disable';
      equipControl(`${url}`, 'get', { chargingCabinetCode: row.code })
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(row.isEnable == 1 ? '停用成功' : ' 启用成功');
            this.formSuccessOperation(res);
          }
        })
        .finally(() => {
          this.roleLoading = false;
        });
    },
    /**
     * [getTableData 获取表格数据]
     * @param  {[type]} searchParam [搜索条件]
     * @return {[type]}             [description]
     */
    getTableData(searchParam) {
      this.roleLoading = true;
      let searchData = searchParam ? { ...searchParam } : {};
      let params = {
        pageNum: searchData.pageNumber ? searchData.pageNumber + 1 : 1,
        pageSize: searchData.pageSize ? searchData.pageSize : 10,
        nameAndCode: searchData.searchKeyWord,
        chargingNetworkId: searchData.searchNetworkId,
        organizationId: searchData.searchOrganizationId,
        chargingCabinetModeId: searchData.searchModelId,
      };
      listCabinets('/selectChargingCabinet', 'get', params)
        .then((res) => {
          if (res.code == 200) {
            let datas = res.data;
            this.tableData = datas;
          } else {
            this.tableData.records = [];
            this.tableData.total = 0;
          }
        })
        .finally(() => {
          this.roleLoading = false;
        });
    },
    /**
     * [multipleAdd 批量添加]
     * @return {[type]}      [description]
     */
    multipleAdd() {
      // 校验code后3位
      const lastThree = Number(this.form.code.substring(this.form.code.length - 4));
      const maxThree = 9999;
      if ( Number(this.form.chargingCabinetNumber) + lastThree > maxThree) {
        this.formButtonDisableFlag = false;
        return this.$message.error('批量新增后充电柜编码后三位不能超过9999！');
      }
      let params = { ...this.form };
      params.productioDate = this.formatterTime(params.productioDate);
      params.installDate = this.formatterTime(params.installDate);
      params.repaireEndDate = this.formatterTime(params.repaireEndDate);
      params.simExpireDate = this.formatterTime(params.simExpireDate);

      delete params.name;
      delete params.code;
      delete params.chargingCabinetNumber;

      let paramData = {
        chargingCabinet: params,
        count: this.form.chargingCabinetNumber,
        namePrefix: this.form.name,
        startCode: this.form.code,
      };

      // var list = [];
      // var obj = {};
      // objectSubAttributeAssign(obj, this.form);
      // for (var i = 0; i < obj.chargingCabinetNumber; i++) {
      //   (function (num) {
      //     var _obj = objectSubAttributeAssign({}, obj);
      //     const _lastThree = lastThree + num;
      //     _obj.name = obj.name + supplementZero(_lastThree, 3);
      //     _obj.code = _obj.code.substring(0, _obj.code.length - 3) + _lastThree;
      //     _obj.isDelete = 0;
      //     list.push(_obj);
      //   })(i);
      // }
      listCabinets('/batch/insert', 'post', paramData)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('批量新增成功');
            this.formSuccessOperation(res);
          }
        })
        .finally(() => {
          this.formButtonDisableFlag = false;
        });
    },
    /**
     * @description: 新增编辑充电柜表单提交
     */
    onSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.doSubmitForm();
        } else {
          return false;
        }
      });
    },
    doSubmitForm() {
      let msg = '';
      if (this.addType == 'multiple') {
        msg = '批量新增';
      } else if (this.form.id) {
        msg = '编辑';
      } else {
        msg = '新增';
      }
      this.$confirm({
        title: '提示',
        content: (h) => `确定要${msg}充电柜吗？`,
        onOk: () => this.doOperate(),
        centered: true,
        maskClosable: true,
      });
    },
    doOperate() {
      this.formButtonDisableFlag = true;
      if (this.addType == 'multiple') {
        this.multipleAdd();
      } else if (this.form.id) {
        this.editRole(this.form);
      } else {
        this.roleAdd(this.form);
      }
    },

    /**
     * [initializationForm 初始化form数据]
     * @return {[type]} [description]
     */
    initializationForm() {
      this.addType = 'single';
      this.oDictionary.allCharges = [];
      this.oDictionary.dynamicNetworksAll = [];
      return {
        name: '',
        code: '',
        organizationId: '',
        chargingCabinetModeId: '',
        binCount: '',
        chargingNetworkId: '',
        chargeTmplId: '',
        productioDate: '',
        installDate: '',
        repaireEndDate: '',
        // simIccid: '',
        simExpireDate: '',
        address: '',
        remark: '',
        lng: '',
        lat: '',

        isEnable: 1,
        isSystem: 0,
        chargeType: null, //组织内是否免费
        isPrivate: null, //是否组织内私有
      };
    },

    /**
     * @description: 新增充电柜权限
     * @param {object} addRoleParam 表单参数
     */
    roleAdd(addRoleParam) {
      addRoleParam.productioDate = this.formatterTime(addRoleParam.productioDate);
      addRoleParam.installDate = this.formatterTime(addRoleParam.installDate);
      addRoleParam.repaireEndDate = this.formatterTime(addRoleParam.repaireEndDate);
      addRoleParam.simExpireDate = this.formatterTime(addRoleParam.simExpireDate);
      listCabinets('/insertChargingCabinet', 'post', addRoleParam)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('新增成功');
            this.formSuccessOperation(res);
          }
        })
        .finally(() => {
          this.formButtonDisableFlag = false;
        });
    },
    dealParams(params) {
      let {
        name,
        code,
        organizationId,
        chargingCabinetModeId,
        binCount,
        chargingNetworkId,
        chargeTmplId,
        productioDate,
        installDate,
        repaireEndDate,
        simExpireDate,
        address,
        remark,
        lng,
        lat,
        chargeType,
        isPrivate,
      } = { ...params };
      return {
        name,
        code,
        organizationId,
        chargingCabinetModeId,
        binCount,
        chargingNetworkId,
        chargeTmplId,
        productioDate,
        installDate,
        repaireEndDate,
        simExpireDate,
        address,
        remark,
        lng,
        lat,
        chargeType,
        isPrivate,
      };
    },
    /**
     * @description: 编辑充电柜权限
     * @param {object} editRoleParam 表单参数
     */
    editRole(editRoleParam) {
      let params = this.dealParams(editRoleParam);
      params.id = editRoleParam.id;
      params.productioDate = this.formatterTime(params.productioDate);
      params.installDate = this.formatterTime(params.installDate);
      params.repaireEndDate = this.formatterTime(params.repaireEndDate);
      params.simExpireDate = this.formatterTime(params.simExpireDate);
      listCabinets('/updateChargingCabinet', 'put', params)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('编辑成功');
            this.formSuccessOperation(res);
          }
        })
        .finally(() => {
          this.formButtonDisableFlag = false;
        });
    },

    /**
     * @description: 表单新增编辑成功后的公共的代码 （消息提示 搜索框重置 请求表格数据）
     * @param {object} successFormData 表单请求成功后返回的对象
     */
    formSuccessOperation(successFormData) {
      this.modleVisible = false;
      this.$refs.insideTable.updateListData();
    },

    /**
     * @description: 新增或编辑
     * @param {object} row 表格某一行的数据对象
     */
    handleEdit(row) {
      this.modleVisible = true;
      this.form = this.initializationForm();

      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      if (this.$refs.map) {
        this.$refs.map.manualDestroy();
      }
      if (row) {
        this.addType = '';
        // 根据ID请求相应充电柜的权限 进行回显
        this.form = { ...row };
        this.dynamicLoadingCharges();

        if (this.form.lat && this.form.lng) {
          this.$nextTick(() => {
            this.$refs.map.addMarker({ lat: this.form.lat, lng: this.form.lng });
          });
        }
      }
    },
    /**
     * [addTypeChange 新增单个或新增批量切换]
     */
    addTypeChange() {
      if (this.addType == 'multiple') {
        this.rules.name = [
          { required: true, message: '请输入充电柜名称', trigger: 'blur' },
          { max: 11, message: '最大长度不能超过11个字', trigger: 'blur' },
        ];
      } else {
        this.rules.name = [
          { required: true, message: '请输入充电柜名称', trigger: 'blur' },
          { max: 15, message: '最大长度不能超过15个字', trigger: 'blur' },
        ];
      }
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
    },

    /**
     * [batchDelete 批量删除]
     * @return {[type]} [description]
     */
    batchDelete() {
      this.isLoading = true;
      listCabinets('/updateChargingCabinetList', 'put', { listIds: this.selectedRowKeys })
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('删除成功');
            this.selectedRowKeys = [];
            this.$refs.insideTable.setSelectedRowKeys(this.selectedRowKeys);
            this.$refs.insideTable.updateListData();
          }
        })
        .finally(() => {
          this.isLoading = false;
        });
    },

    /**
     * @description: 点击删除
     * @param {object} row 格某一行的数据对象
     */
    handleDelete(row) {
      listCabinets(`/updateChargingCabinet/${row.id}`, 'put').then((res) => {
        if (res.code == 200) {
          this.$message.success('删除成功');
          this.$refs.insideTable.updateListData(true);
        }
      });
    },
    formatterTime(val) {
      return val ? moment(val).format('YYYY-MM-DD') : '';
    },

    /**
     * [mapClick 地图点击事件]
     * @param  {[type]} e [点击携带数据]
     * @return {[type]}   [description]
     */
    mapClick(e) {
      this.form.lng = this.toPrecisionSix(e.latLng.lng);
      this.form.lat = this.toPrecisionSix(e.latLng.lat);
      if (e.address) {
        this.form.address = e.address;
      }
    },

    /**
     * [setUserTemplate 设置用户模板form赋值]
     * @param {[type]} e [description]
     */
    setUserTemplate(e) {
      for (var i = 0; i < this.oDictionary.allCabinetSecurities.length; i++) {
        if (this.oDictionary.allCabinetSecurities[i].code == e) {
          this.form.loginName = this.oDictionary.allCabinetSecurities[i].loginName;
          this.form.loginPass = this.oDictionary.allCabinetSecurities[i].loginPass;
          this.form.aesKey = this.oDictionary.allCabinetSecurities[i].aesKey;
          break;
        }
      }
    },
    /**
     * [setBinCount 设置格口数量form赋值]
     * @param {[type]} e [description]
     */
    setBinCount(e) {
      for (var i = 0; i < this.oDictionary.allCabinetModels.length; i++) {
        if (this.oDictionary.allCabinetModels[i].code == e) {
          this.form.binCount = this.oDictionary.allCabinetModels[i].binCount;
          break;
        }
      }
    },
    /**
     * [toPrecisionSix 保留小数点6位数]
     * @param  {[type]} val [数字]
     * @return {[type]}     [description]
     */
    toPrecisionSix(val) {
      return parseInt(val * 1000000) / 1000000;
    },
    /**
     * [tableChange table多选变化]
     * @param  {[type]} index  [序号]
     * @param  {[type]} arrObj [数组对象]
     * @return {[type]}        [description]
     */
    tableChange(index, arrObj) {
      this.selectedRowKeys = arrObj.map((n) => {
        return n.id;
      });
    },
  },
};
</script>

<style lang="less" scoped>
.Role {
  width: 100%;
  height: calc(100vh - 150px);
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  position: relative;
  .position {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.1);
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }
  .table {
    flex: 1;
    background: white;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    .tableTitle {
      width: 100%;
      height: 64px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ececec;
      padding: 0 20px;
      margin-bottom: 10px;
      .title {
        width: 40%;
        height: 100%;
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: 550;
      }
      .addButton {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
    .tableList {
      // max-height: calc(100vh - 380px);
      // overflow: auto;
      /deep/ .tableScroll {
        max-height: calc(100vh - 380px);
        overflow: auto;
      }
    }
  }
}
#modalContent {
  width: 100%;
  height: 600px;
  overflow: auto;
  position: relative;
  .formAspin {
    position: absolute;
    width: 100%;
    height: 600px;
    background: #ececec;
    border-radius: 4px;
    z-index: 999;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
/deep/ .ant-col .ant-col-4 {
  width: 20.666667%;
}
</style>
